import { Box } from '@chakra-ui/react';
import ImageGalleryContent from 'features/gallery/components/ImageGalleryContent';

import ResizeHandle from 'features/ui/components/tabs/ResizeHandle';
import { AnimatePresence, motion } from 'framer-motion';
import { useRef } from 'react';
import { Panel, PanelGroup } from 'react-resizable-panels';

import ImageTransformWrapper from './ImageTransformWrapper';
import { useAppSelector } from 'app/store/storeHooks';
import { useGetImageDTOQuery } from 'services/api/endpoints/images';
import { skipToken } from '@reduxjs/toolkit/dist/query';

export default function Lightbox() {
  const isLightBoxOpen = useAppSelector(
    (state) => state.lightbox.isLightboxOpen
  );

  const lastSelectedImage = useAppSelector(
    (state) => state.gallery.selection[state.gallery.selection.length - 1]
  );
  const { currentData: imageDTO } = useGetImageDTOQuery(
    lastSelectedImage?.image_name ?? skipToken
  );

  const imageTransformRef = useRef(null);

  const handleLightboxGallery = () => {
    if (
      imageTransformRef &&
      imageTransformRef.current &&
      imageTransformRef.current.resetTransform
    ) {
      imageTransformRef.current.resetTransform();
    }
  };

  return (
    <AnimatePresence>
      {isLightBoxOpen && (
        <motion.div
          key="lightbox"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.15, ease: 'easeInOut' }}
          style={{
            display: 'flex',
            width: '100vw',
            height: '100vh',
            padding: '0.5rem',
            position: 'fixed',
            top: '0',
            background: 'var(--tourfly-colors-base-950)',
            zIndex: 99,
          }}
        >
          <PanelGroup
            autoSaveId="lightboxGroup"
            direction="horizontal"
            style={{ height: '100%', width: '100%' }}
          >
            <Panel id="lightboxImage">
              <ImageTransformWrapper
                ref={imageTransformRef}
                imageDTO={imageDTO}
              />
            </Panel>
            <ResizeHandle />
            <Panel
              id="lightboxGallery"
              order={3}
              defaultSize={10}
              minSize={6}
              maxSize={50}
              collapsible
              onResize={handleLightboxGallery}
            >
              <Box h="calc(100vh - 1rem)">
                <ImageGalleryContent />
              </Box>
            </Panel>
          </PanelGroup>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
